package com.liveinstars.im.core.service.impl;

import com.liveinstars.im.domain.dao.model.ChatServer;
import com.liveinstars.im.domain.manager.ChatServerManager;
import com.liveinstars.im.domain.manager.UserOnlineInfoManager;
import com.liveinstars.api.im.query.ChatServerQuery;
import com.onepiece.cache.service.CacheService;
import com.liveinstars.im.core.Session;
import com.liveinstars.im.core.SessionManager;
import com.liveinstars.im.core.service.ChatServerService;
import com.liveinstars.im.corebean.TokenServer;
import com.onepiece.shipelves.common.utils.CacheUtil;
import com.onepiece.shipelves.common.utils.JsonUtil;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @author: zhouze
 * @date: 2020/4/29
 */
@Service("chatServerService")
public class ChatServerServiceImpl implements ChatServerService {

    private final static Logger logger = LoggerFactory.getLogger(ChatServerServiceImpl.class);

    @Value("${netty.server.id}")
    private Long chatServerId;

    @Value("${netty.server.name}")
    private String chatServerName;

    @Value("${netty.server.port}")
    private Integer serverPort;

    @Value("${netty.server.outip}")
    private String serverOutIp;

    @Value("${netty.server.ip}")
    private String serverIp;

    @Autowired
    private ChatServerManager chatServerManager;

    @Autowired
    private UserOnlineInfoManager userOnlineInfoManager;

    @Autowired
    CacheService cache;

    @Override
    public void offline() {
        ChatServer chatServer = new ChatServer();
        chatServer.setId(chatServerId);
        chatServer.setOnline(false);
        logger.info("数据库server状态关闭 ---------------");
        chatServerManager.updateById(chatServer);
        logger.info("数据库server状态关闭 ---------------");
        logger.info("移除数据库登录用户开始 ---------------");
        userOnlineInfoManager.deleteByChatServerId(chatServerId);
        logger.info("移除数据库登录用户结束 ---------------");
        Map<String, Session> sessionMap = SessionManager.getSessionMap();
        logger.info("移除redis用户Token开始 ---------------");
        for (String channelId : sessionMap.keySet()) {
            Session session = sessionMap.get(channelId);
            if (session.getType() == Session.SessionType.SC){
                TokenServer tokenServer = new TokenServer(session.getClientId(), channelId, serverIp, serverPort);
                logger.info("移除redis用户 {} {}", session.getUserId(), JsonUtil.toJson(tokenServer));
                cache.srem(CacheUtil.getImUserTokenChatserverList(session.getUserId()), JsonUtil.toJson(tokenServer));
            }
        }
        logger.info("移除redis用户Token结束 ---------------");
    }

    @Override
    public void register() {
        ChatServer chatServer = new ChatServer();
        chatServer.setId(chatServerId);
        chatServer.setOnline(true);
        chatServer.setName(chatServerName);
        chatServer.setPort(serverPort.toString());
        chatServer.setIp(serverIp);
        chatServer.setOutIp(serverOutIp);
        chatServerManager.saveOrUpdate(chatServer);
    }

    @Override
    public List<ChatServer> listOnlineServer() {
        ChatServerQuery chatServerQuery = new ChatServerQuery();
        chatServerQuery.setOnline(true);
        List<ChatServer> list = chatServerManager.listByQuery(chatServerQuery);
        return list;
    }

    @Override
    public ChatServer getChatServerById(Long id) {
        ChatServer chatServer = chatServerManager.getById(id);
        return chatServer;
    }

    @Override
    public ChatServer getChatServerByIpAndPort(String ip, Integer port) {
        ChatServerQuery query = new ChatServerQuery();
        query.setIp(ip);
        query.setPort(port.toString());
        List<ChatServer> list = chatServerManager.listByQuery(query);
        if (CollectionUtils.isNotEmpty(list)) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public ChatServer getChatServerByName(String name) {
        ChatServerQuery query = new ChatServerQuery();
        query.setName(name);
        List<ChatServer> list = chatServerManager.listByQuery(query);
        if (CollectionUtils.isNotEmpty(list)) {
            return list.get(0);
        }
        return null;
    }
}
